<template>
  <div class="editor-container">
    <div id="editor"></div>
    <!-- html 源码编辑 -->
    <el-dialog title="源代码编辑" :visible.sync="htmlFlag" width="60%">
      <div class="edit-main" v-if="htmlFlag">
        <textarea ref="editCode"   class="editCode"></textarea>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" @click="saveCode"
          >保存</el-button
        >
      </span>
    </el-dialog>
  </div>
</template>

<script>
  import E from "wangeditor";
  import beautify from 'beautify'
  // 富文本扩展能力，源代码编辑‘
  import _CodeMirror from 'codemirror'
  import 'codemirror/addon/selection/active-line'
  // 核心样式
  import 'codemirror/lib/codemirror.css';
  // 引入主题后还需要在 options 中指定主题才会生效
  import 'codemirror/theme/monokai.css'
  import 'codemirror/mode/javascript/javascript.js'
  import 'codemirror/mode/css/css.js'
  import 'codemirror/mode/xml/xml.js'
  import 'codemirror/mode/clike/clike.js'
  import 'codemirror/mode/markdown/markdown.js'
  import 'codemirror/mode/python/python.js'
  import 'codemirror/mode/r/r.js'
  import 'codemirror/mode/shell/shell.js'
  import 'codemirror/mode/sql/sql.js'
  import 'codemirror/mode/swift/swift.js'
  import 'codemirror/mode/vue/vue.js'
  const CodeMirror = window.CodeMirror || _CodeMirror
// 核心样式
export default {
  props:['html'],
  data() {
    return {
      editor: "",
      htmlFlag: false,
      codeEditor:'',
      editHtml:'',
      options: {
        // 缩进格式
        tabSize: 2,
        // 主题，对应主题库 JS 需要提前引入
        theme: 'monokai',
        mode:'text/html',
        Mode:'text/html',
        // 显示行号
        lineNumbers: true,
        line: true,
        lineWrapping:true,
        smartIndent:true,
        styleActiveLine:true
      },
    };
  },
  components: {
  },
  mounted() {
    this.editHtml = this.html || ''
    this.initEaitOr();
  },
  methods: {
    getHtml(){
      return this.editor.txt.html()
    },
    initCode(){
        this.codeEditor = CodeMirror.fromTextArea(this.$refs.editCode, this.options)
        // 编辑器赋值
        console.log('beautify :>> ', beautify);
        let html  = beautify(this.editHtml, {format: 'html'})
        this.codeEditor.setValue(html)
        this.codeEditor.setSize('auto','500px')
          // 支持双向绑定
        this.codeEditor.on('change', (coder) => {
          // this.editHtml = coder.getValue()
          //   this.editor.txt.html(this.editHtml)
        })
    },
    saveCode(){
      let val = this.codeEditor.getValue()
      this.editHtml = val
      this.editor.txt.html(this.editHtml)
      this.htmlFlag = false
        this.codeEditor.setValue('')
    },
    initEaitOr() {
      let { BtnMenu } = E;
      let that = this;
      class HtmlMenu extends BtnMenu {
        constructor(editor) {
          // data-title属性表示当鼠标悬停在该按钮上时提示该按钮的功能简述
          const $elem = E.$(
            `<div class="w-e-menu" data-title="源码">
                  <img style="width:20px" src="https://willmid-img.oss-cn-shanghai.aliyuncs.com/2021/06/13/html-1.png"/>
                  </div>`
          );
          super($elem, editor);
        }
        // 菜单点击事件
        clickHandler() {
          that.clickHandler();
        }
        tryChangeActive() {}
      }
       class CalcMenu extends BtnMenu {
        constructor(editor) {
          // data-title属性表示当鼠标悬停在该按钮上时提示该按钮的功能简述
          const $elem = E.$(
            `<div class="w-e-menu" data-title="清除格式">
                  <img style="width:20px" src="https://willmid-img.oss-cn-shanghai.aliyuncs.com/2021/06/16/ab6312f221fced8fa7bba1186340cc1f.png"/>
                  </div>`
          );
          super($elem, editor);
        }
        // 菜单点击事件
        clickHandler() {
           that.calcHtml()
        }
        tryChangeActive() {}
      }
      E.registerMenu("htmlKey", HtmlMenu);
      E.registerMenu("calcKey", CalcMenu);
      const editor = new E("#editor");
      let EeidConfig = {
        height: 400,
        width:800,
        zIndex: 500,
        placeholder: "请输入详情",
        focus: false, // 自动聚焦
        uploadImgServer:'',
        onchange: (val) => {
          // 修改
          this.htmlOnChange(val)
        },
        customAlert: (s, t) => {
          this.customAlert(s, t);
        },
      };
      Object.assign(editor.config, EeidConfig);
      this.editor = editor;
       this.editor.txt.html()
      this.editor.create();
    },
    calcHtml(){
        // 清除格式
        // 获取jsOn 格式化的内容
        try{
          let JsonHtml = this.editor.txt.getJSON()
            for(let item of JsonHtml){
              item.tag = 'p'
              item.attrs = []
              if(item.children.length){
                for(let keyItem of item.children){
                  keyItem.tag ? keyItem.tag = 'p' : ''
                  keyItem.attrs ?  keyItem.attrs = [] :''
                }
              }
            }
            this.editor.txt.setJSON(JsonHtml)
        }catch(err){
          this.$message('格式化失败')
          console.log('格式化失败 :>> ', err);
        }
       
    },
    htmlOnChange(val) {
      // 编辑器的 change 回调
      this.editHtml = val;
    },
    clickHandler() {
      //显示源代码
      this.htmlFlag = true;
      setTimeout(()=>{
        this.initCode()
      },500)
    },
    customAlert(s, t) {
      // 编辑器错误回调
      let message = this.$message;
      switch (t) {
        case "success":
          message.success(s);
          break;
        case "info":
          message.info(s);
          break;
        case "warning":
          message.warning(s);
          break;
        case "error":
          message.error(s);
          break;
        default:
          message.info(s);
          break;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.editor-container{
  width:800px;
}
.edit-main{
  .editCode{ 
    width: 100%;
  }
}

</style>